package com.yupi.springbootinit.bizmq;


import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private AiManager aiManager;

    @Resource
    private ChartService chartService;

    /**
     * 接受消息的方法
     * */
    // 简化异常处理
    @SneakyThrows
    // 使用
    @RabbitListener(queues = BiMqConstant.BI_QUEUE, ackMode = "MANUAL")
    public void  receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        // 使用日志打印接收到的消息内容
        log.info("接收到消息：{}",message);
        if (StringUtils.isBlank(message)){
            // 如果更新失败，拒绝当前消息，让消息重新进入队列
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "消息内容为空");
        }

        Long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);

        // 如果图表为空，拒绝消息并抛出业务异常
        if (chart == null){
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表不存在");
        }

        Chart updatedChart = new Chart();
        updatedChart.setId(chartId);
        updatedChart.setStatus(BiMqConstant.RUNNING);
        boolean flag = chartService.updateById(updatedChart);

        if (!flag){
            // 如果更新失败，拒绝当前消息，让消息重新进入队列
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新图表状态失败");
        }

        // 调用AI
        String result = aiManager.doChat(BiMqConstant.BI_MODEL_ID, buildUserInput(chart));
        // 对返回的结果进行拆分，按照预设里面的5个中括号进行拆分
        String[] splits = result.split("【【【【【");
        if (splits.length < 3){
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        // 更新图表的生成结果
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setStatus(BiMqConstant.SUCCESS);
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        boolean updateResult =  chartService.updateById(updateChartResult);
        if(!updateResult){
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "图表状态更新失败");
        }
        // 消息确认
        channel.basicAck(deliveryTag,false);
    }

    private void handleChartUpdateError(Long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult =  chartService.updateById(updateChartResult);
        if(!updateResult){
            log.error("AI 生成图表失败，chartId: {}，execMessage：{}", chartId, execMessage);
        }
    }

    /**
     * 构造用户输入
     * */
    public String buildUserInput(Chart chart) {
        // 获取数据
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();
        // 用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)){
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");

        // 压缩后的数据
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }
}
